const querystring = require('querystring');
const fs = require('fs')
const handleBlogRouter = require('./src/router/blog');
const handleUserRouter = require('./src/router/user');
const root = (__dirname,'./dist'); //你本地放index.html页面的文件路径
// 处理postdata  
const getPostData = (req) => {
    const promise = new Promise((resolve, reject) => {
        if(req.method !== 'POST') {
            resolve({});
            return;
        }
        let postData = '';
        req.on('data', chunk => {
            postData += chunk.toString();
        })
        req.on('end', () => {
            if(!postData) {
                resolve();
                return;
            }
            resolve(postData);
        })
    })
    return promise;
}
// 开启服务，把index.html文件放入node服务中 访问地址 http://localhost:8000/index.html（临时搭建测试用的）
const handleHtml = (req, res) => {
    const file = root + req.url;
    fs.readFile(file, function(err,data){
        if(err) {
            res.writeHeader(404, {
                'content-type' : 'text/html;charset="utf-8"'
            });
            res.write('<h1>404错误</h1><p>你要找的页面不存在</p>');
            res.end();
        } else {
            res.writeHeader(200,{
               'content-type' : 'text/html;charset="utf-8"'
            });
            res.write(data);//将index.html显示在客户端
            res.end();
        }
    })
};
const serverHandle = (req, res) => {
    //设置
    res.setHeader("Access-Control-Allow-Origin", 'http://localhost:8000'); // 限制跨域
    //res.setHeader("Access-Control-Allow-Origin", '*');
    res.setHeader("Access-Control-Allow-Methods", "*");
    res.setHeader("Access-Control-Allow-Headers", "Content-Type,request-origin"); // 设置请求头中允许携带的参数
    res.setHeader("Cache-Control", "no-store");
    // 开启服务，把index.html文件放入node服务中   http://localhost:8000/index.html
    const url = req.url;
    if(url.includes('html')) {
        handleHtml(req, res);
        return;
    }
    //设置
    res.setHeader("Content-type", "application/json"); // 设置接口的返回类型
    const method = req.method;
    req.path = url.split('?')[0];
    req.query = querystring.parse(url.split('?')[1]);
    // 获取cookie
    req.cookie = {};
    const cookieStr = req.headers.cookie || '';
    cookieStr.split(';').forEach(item => {
        if(!item) {
            return;
        }
        const arr = item.split('=');
        const key = arr[0].trim();
        const value = arr[1].trim();
        req.cookie[key] = value;
    })
    getPostData(req).then(postData => {
        req.body = postData;
       // 处理路由
        const blogResult = handleBlogRouter(req, res);
        const userData = handleUserRouter(req, res);
        if(blogResult) {
            blogResult.then(blogData => {
                res.end(JSON.stringify(blogData));
                return;
            })
            return;
        }
        if(userData) {
            userData.then(result => {
                res.end(JSON.stringify(result));
                return;
            })
            return;
        }
        res.writeHead(404, { "Content-type": "application/json"});
        res.write('404 not fund\n');
        res.end();
    })
}
module.exports = serverHandle;